#!/bin/bash

# Cursor MCP HTTP 模式自动配置脚本

echo "=== Cursor MCP HTTP 模式配置工具 ==="
echo

# 检查必要文件
if [ ! -f "../bin/mysql-mcp-server" ]; then
    echo "⚠️  未找到 mysql-mcp-server，正在构建..."
    cd ../src && go build -o ../bin/mysql-mcp-server && cd ../setup
    if [ $? -ne 0 ]; then
        echo "❌ 构建失败，请检查 Go 环境"
        exit 1
    fi
    echo "✅ 构建成功"
fi

if [ ! -f "../service/start-http.sh" ]; then
    echo "❌ 未找到 start-http.sh 脚本"
    exit 1
fi

chmod +x ../service/start-http.sh

# 获取当前路径
CURRENT_PATH=$(pwd)
echo "🔍 当前项目路径: $CURRENT_PATH"

# 收集用户配置
echo
echo "请提供 MySQL 数据库配置信息："
echo

read -p "MySQL 主机地址 [localhost]: " MYSQL_HOST
MYSQL_HOST=${MYSQL_HOST:-localhost}

read -p "MySQL 端口 [3306]: " MYSQL_PORT
MYSQL_PORT=${MYSQL_PORT:-3306}

read -p "MySQL 用户名: " MYSQL_USER
if [ -z "$MYSQL_USER" ]; then
    echo "❌ MySQL 用户名不能为空"
    exit 1
fi

read -s -p "MySQL 密码: " MYSQL_PASSWORD
echo
if [ -z "$MYSQL_PASSWORD" ]; then
    echo "❌ MySQL 密码不能为空"
    exit 1
fi

read -p "数据库名: " MYSQL_DATABASE
if [ -z "$MYSQL_DATABASE" ]; then
    echo "❌ 数据库名不能为空"
    exit 1
fi

echo
read -p "HTTP 服务器端口 [8080]: " SERVER_PORT
SERVER_PORT=${SERVER_PORT:-8080}

# 测试数据库连接
echo
echo "🔍 测试数据库连接..."
mysql -h "$MYSQL_HOST" -P "$MYSQL_PORT" -u "$MYSQL_USER" -p"$MYSQL_PASSWORD" -e "USE $MYSQL_DATABASE; SELECT 1;" 2>/dev/null
if [ $? -eq 0 ]; then
    echo "✅ 数据库连接成功"
else
    echo "❌ 数据库连接失败，请检查配置"
    exit 1
fi

# 生成 Cursor 配置文件
echo
echo "📝 生成 Cursor MCP 配置文件..."

# 创建配置内容
cat > ../config/cursor-mcp-config.json << EOF
{
  "mcpServers": {
    "mysql-stdio": {
      "command": "$CURRENT_PATH/bin/mysql-mcp-server",
      "env": {
        "SERVER_MODE": "stdio",
        "MYSQL_HOST": "$MYSQL_HOST",
        "MYSQL_PORT": "$MYSQL_PORT",
        "MYSQL_USER": "$MYSQL_USER",
        "MYSQL_PASSWORD": "$MYSQL_PASSWORD",
        "MYSQL_DATABASE": "$MYSQL_DATABASE",
        "MYSQL_MAX_OPEN_CONNS": "25",
        "MYSQL_MAX_IDLE_CONNS": "25"
      }
    },
    "mysql-http": {
      "url": "http://localhost:$SERVER_PORT/mcp",
      "fetch": {
        "timeout": 30000
      }
    }
  }
}
EOF

echo "✅ 配置文件已生成: ../config/cursor-mcp-config.json"

# 查找 Cursor 配置目录
CURSOR_CONFIG_DIRS=(
    "$HOME/.cursor"
    "$HOME/.config/cursor"
    "$HOME/Library/Application Support/Cursor"
    "$HOME/.cursor-mcp"
)

CURSOR_CONFIG_DIR=""
for dir in "${CURSOR_CONFIG_DIRS[@]}"; do
    if [ -d "$dir" ]; then
        CURSOR_CONFIG_DIR="$dir"
        break
    fi
done

echo
if [ -n "$CURSOR_CONFIG_DIR" ]; then
    echo "🔍 找到 Cursor 配置目录: $CURSOR_CONFIG_DIR"
    
    read -p "是否将配置复制到 Cursor 配置目录？ [y/N]: " COPY_CONFIG
    if [ "$COPY_CONFIG" = "y" ] || [ "$COPY_CONFIG" = "Y" ]; then
        # 创建 MCP 配置目录（如果不存在）
        mkdir -p "$CURSOR_CONFIG_DIR/mcp"
        
        # 复制配置文件
        cp ../config/cursor-mcp-config.json "$CURSOR_CONFIG_DIR/mcp/config.json"
        echo "✅ 配置已复制到: $CURSOR_CONFIG_DIR/mcp/config.json"
    fi
else
    echo "⚠️  未找到 Cursor 配置目录，请手动复制配置文件"
    echo "   您需要将 cursor-mcp-config.json 复制到 Cursor 的 MCP 配置目录"
fi

# 测试配置
echo
echo "🧪 测试配置..."

# 测试 stdio 模式
echo "测试 stdio 模式..."
timeout 3s ../bin/mysql-mcp-server <<< '{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}' 2>/dev/null | grep -q "tools" && echo "✅ stdio 模式测试成功" || echo "⚠️  stdio 模式测试未完成（正常现象）"

# 测试 HTTP 模式（后台启动）
echo "测试 HTTP 模式..."
export MYSQL_HOST MYSQL_PORT MYSQL_USER MYSQL_PASSWORD MYSQL_DATABASE SERVER_PORT
export SERVER_HOST=localhost HTTP_ENABLE_CORS=true HTTP_ENABLE_HEALTH_CHECK=true

# 后台启动 HTTP 服务器
../service/start-http.sh &
HTTP_PID=$!

# 等待服务器启动
sleep 3

# 测试健康检查
if curl -s "http://localhost:$SERVER_PORT/health" | grep -q "healthy"; then
    echo "✅ HTTP 模式测试成功"
    echo "   健康检查: http://localhost:$SERVER_PORT/health"
    echo "   MCP 端点: http://localhost:$SERVER_PORT/mcp"
else
    echo "❌ HTTP 模式测试失败"
fi

# 停止测试服务器
kill $HTTP_PID 2>/dev/null
wait $HTTP_PID 2>/dev/null

echo
echo "=== 配置完成 ==="
echo
echo "📋 使用说明:"
echo "1. 在 Cursor 中选择以下 MCP 服务器之一："
echo "   - mysql-stdio: 标准模式（推荐用于 Cursor 集成）"
echo "   - mysql-http: HTTP 网络模式（需要先启动服务器）"
echo
echo "2. HTTP 模式使用步骤："
echo "   步骤1: 手动启动 HTTP 服务器"
echo "          ../service/start-http.sh"
echo "   步骤2: 在 Cursor 中选择 mysql-http 配置"
echo "          Cursor 将连接到: http://localhost:$SERVER_PORT/mcp"
echo
echo "3. 测试服务器："
echo "   ../test/test-client.sh http://localhost:$SERVER_PORT http"
echo
echo "📁 配置文件位置:"
echo "   - 项目配置: $CURRENT_PATH/config/cursor-mcp-config.json"
if [ -n "$CURSOR_CONFIG_DIR" ]; then
    echo "   - Cursor 配置: $CURSOR_CONFIG_DIR/mcp/config.json"
fi
echo
echo "⚠️  重要说明:"
echo "   - stdio 模式: Cursor 自动启动服务器"
echo "   - http 模式: 需要先手动启动 HTTP 服务器，然后 Cursor 连接到服务地址"
echo
echo "📖 更多信息请查看:"
echo "   - README.md - 完整使用指南"
echo "   - CURSOR_HTTP_SETUP.md - Cursor 配置详解"
echo "   - HTTP_MODE_ENHANCEMENT.md - HTTP 模式功能说明" 